import store from '@/store'

var lockReconnect = false; //避免ws重复连接
let webSocket = null
var globalCallback = null

const MSG_EVENT = {
    "P2P": "P2P",
    "GROUP": "GROUP",
    "PING": "PING",
    "PONG": "PONG",
    "SERVER": "SERVER"
};

// 初始化webSocket
function initWebSocket(callback) {
    // ws地址 -->这里是你的请求路径
    let ws = 'ws://' + store.getters.nettyAddr + '/ws?' + store.getters.token
    webSocket = new WebSocket(ws)

    webSocket.onopen = function () {
        heartCheck.reset().start(); //心跳检测重置
    };
    webSocket.onclose = function (e) {
        reconnect()
    };
    webSocket.onmessage = function (e) {
        //如果获取到消息，心跳检测重置
        heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
        globalCallback = callback
        if (globalCallback) {
            globalCallback(JSON.parse(e.data))
        }
    };
    // 连接发生错误的回调方法
    webSocket.onerror = function () {
        reconnect()
        console.log('WebSocket连接发生错误')
    }
}

/**
 * 数据发送
 * @param agentData
 */
function webSocketSend(agentData) {
    if (!webSocket) {
        return;
    }
    if (webSocket.readyState === WebSocket.OPEN) {
        webSocket.send(JSON.stringify(agentData));
    }
}

/**
 * 关闭 socket
 */
function closeWebSocket() {
    webSocket.close();
}


/**
 * 发送消息
 * @param rid
 * @param msg
 */
function sendMsg(rid, msg) {
    let obj = {};
    obj.userId = store.getters.userId;
    obj.receiveUserId = rid;
    obj.message = msg;
    obj.event = 'P2P';
    webSocketSend(obj)
}

/**
 * 群组消息
 * @param groupId
 * @param msg
 */
function sendGroupMsg(groupId, msg) {
    let obj = {};
    obj.userId = store.getters.userId;
    obj.groupId = groupId;
    obj.message = msg;
    obj.event = 'GROUP';
    webSocketSend(obj)
}

/**
 * 重新连接
 * @param url
 */
function reconnect() {
    if (store.getters.nettyAddr && store.getters.token) {
        if (lockReconnect) return;
        lockReconnect = true;
        setTimeout(function () { //没连接上会一直重连，设置延迟避免请求过多
            initWebSocket(globalCallback);
            lockReconnect = false;
        }, 2000);
    }
}


//心跳检测
var heartCheck = {
    timeout: 60000, //60秒
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function () {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function () {
        var self = this;
        this.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            let obj = {};
            obj.userId = store.getters.userId;
            obj.message = '客户端发送心跳检测';
            obj.type = 'TEXT';
            obj.event = 'PING';
            webSocketSend(obj);
            self.serverTimeoutObj = setTimeout(function () {
                closeWebSocket();
            }, self.timeout)
        }, this.timeout)
    }
}

export {
    initWebSocket, sendMsg, sendGroupMsg, closeWebSocket, MSG_EVENT
}